package com.xmall.order.handler.msg;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.xmall.config.AmqpCommonConfig;
import com.xmall.msg.queue.OrderModule;
import com.xmall.msg.entity.order.OrderCancelCheckMsg;
import com.xmall.order.entity.Order;
import com.xmall.order.service.other.IMsgService;
import com.xmall.order.service.IOrderService;
import com.xmall.order.utils.OrderStatusUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 取消订单检查：订单在规定时间内没有支付，发送取消订单消息
 */
@Slf4j
@Component
@RabbitListener(queues = OrderModule.OrderCancelCheck.ORDER_CANCEL_CHECK_QUEUE, containerFactory = AmqpCommonConfig.RABBIT_LISTENER_CONTAINER_FACTORY_NAME)
public class OrderCancelCheckHandler {

    @Resource
    private IOrderService orderService;

    @Resource
    private IMsgService msgService;

    @RabbitHandler
    public void msg(Channel channel, Message message, OrderCancelCheckMsg msg) throws IOException {
        log.info("rabbitmq handler: order service: OrderCancelCheckHandler: {}", JSONUtil.toJsonStr(msg));
        Order entity = orderService.getById(msg.getOrderId());
        if(null != entity && OrderStatusUtils.beforeCancelCheck(entity.getOrderStatus())) {
            msgService.sendOrderCancelMsg(msg.getOrderId());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
